<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <select name="" id="seProvince">
        <option value="">请选择省份</option>
    </select>
    <select name="" id="seCity">
        <option value="">请选择城市</option>
    </select>
    <select name="" id="seDistrict">
        <option value="0">请选择区县0</option>
        <option value="1">请选择区县1</option>
    </select>

    <p id="pAddress">这里是完整地址</p>

    <script src="../../../../wheels/net_utils/ajax_util.js"></script>
    <script>
        // const se = new HTMLSelectElement()
        seDistrict.onchange = function (e) {
            console.log("seDistrict.selectedIndex", seDistrict.selectedIndex);
            console.log("seDistrict.selectedOptions", seDistrict.selectedOptions[0]);

            // pAddress显示完整地址
            pAddress.innerText = `${seProvince.selectedOptions[0].innerText}${seCity.selectedOptions[0].innerText}${seDistrict.selectedOptions[0].innerText}`
        }

        seCity.onchange = function (e) {
            console.log("seDistrict.selectedOptions", seCity.selectedOptions[0]);

            optionsHtml = ""
            const districts = provinceDetail.cities[seCity.selectedOptions[0].value*1].districts
            districts.forEach(
                d => {
                    optionsHtml += `<option value='${d.Id}'>${d.DisName}</option>`
                }
            )
            seDistrict.innerHTML = optionsHtml
        }

        seProvince.onchange = function (e) {
            console.log("seDistrict.selectedOptions", seProvince.selectedOptions[0]);
            getProvinceDetail(seProvince.selectedOptions[0].value)
        }

        /* 获取省份详情 */
        let provinceDetail;
        async function getProvinceDetail(proid) {
            provinceDetail = localStorage.getItem(`prodetail_${proid}`)
            if (provinceDetail) {
                console.log("从本地获取provinceDetail成功！");
                provinceDetail = JSON.parse(provinceDetail)

                // 渲染城市和区县
                renderCitiesAndDistricts()
                return
            }

            try {
                let _proDetail = await ajaxPromise({
                    url: `http://localhost:8000/china/province/${proid}`
                })
                let proDetail = JSON.parse(_proDetail)

                // 加载数据成功时缓存在本地
                if (proDetail.code == 1) {
                    localStorage.setItem(
                        `prodetail_${proid}`,
                        JSON.stringify(proDetail.provinceDetail)
                    )
                    console.log("联网获取provinceDetail成功！", proDetail);
                    provinceDetail = proDetail.provinceDetail

                    // 渲染城市和区县
                    renderCitiesAndDistricts()
                } else {
                    console.log("加载省份详情失败", proDetail)
                }

            } catch (err) {
                console.log("加载省份详情失败", err);
            }
        }


        /* 联网加载所有省份 */
        let provinces = [];
        function loadData() {
            ajaxPromise({
                url: "http://localhost:8000/china/province/0"
            })
                .then(retJson => {
                    console.log("ret", retJson);
                    const data = JSON.parse(retJson)
                    if (!data.err && data.results && data.results.length) {
                        // 本地缓存所有省份数据
                        localStorage.setItem("provinces", JSON.stringify(data.results))

                        provinces = data.results
                        console.log("provinces from server", provinces);
                    }
                })
                .then(
                    value => renderProvinces()
                )
                .catch(err => console.log("err", err))
        }

        /* 渲染省份 */
        let provinceRenderOK = false
        function renderProvinces() {
            if (provinceRenderOK) return

            let optionsHtml = ""
            provinces.forEach(
                p => {
                    optionsHtml += `<option value='${p.ProID}'>${p.ProName}</option>`
                }
            )
            seProvince.innerHTML = optionsHtml
            provinceRenderOK = true
        }

        /*  */
        function renderCitiesAndDistricts() {
            if (!provinceDetail) {
                console.log("请先加载省份详情");
                return
            }

            let optionsHtml

            // 渲染地级市
            optionsHtml = ""
            const cities = provinceDetail.cities
            for (let cityid in cities) {
                c = cities[cityid]
                optionsHtml += `<option value='${c.CityID}'>${c.CityName}</option>`
            }
            seCity.innerHTML = optionsHtml

            // 渲染默认地级市的区县
            optionsHtml = ""
            const minCityId = Math.min(...Object.keys(provinceDetail.cities))
            const districts = provinceDetail.cities[minCityId].districts
            districts.forEach(
                d => {
                    optionsHtml += `<option value='${d.Id}'>${d.DisName}</option>`
                }
            )
            seDistrict.innerHTML = optionsHtml
        }

        // 页面加载时获取所有省份
        // 如果本地无缓存则请求后台获取省份数据
        provinces = localStorage.getItem("provinces")
        if (!provinces) {
            loadData()
        }

        // 否则直接本地加载
        else {
            // 加载省份
            console.log("provinces from localStorage", provinces);
            provinces = JSON.parse(provinces)
            renderProvinces()
        }

    </script>
</body>

</html>